// components/OrderPage.js
import React, { useState, useEffect } from 'react';
import $ from 'jquery';
import styles from '../css/oederPage.module.css';
import leftImg from '../assets/left.png';
import hourse3Img from '../assets/hourse3.png';
import bttImg from '../assets/down.png';
import qrCodeImg from '../assets/qrcode.png';
import noneImg from '../assets/none.png';
import startoneImg from '../assets/graystar.png';
import starttwoImg from '../assets/redstar.png';
import starthreeImg from '../assets/starthree.png';
import { useNavigate } from 'react-router-dom';
// 导入API封装
import { fetchOrderList, deleteOrder, updateOrderStatus } from '../api/orderPage';
import { imgUrl } from '../config';//前缀
const OrderPage = () => {
  // 状态管理
  const [data, setData] = useState(JSON.parse(sessionStorage.getItem("jingqu")) || []);
  const [orderdata, setOrderdata] = useState([]);
  const [orderdatas, setOrderdatas] = useState([]);
  const [statusMine, setStatusMine] = useState(sessionStorage.getItem("statusMine"));
  const [statusIndex, setStatusIndex] = useState(sessionStorage.getItem("statusIndex"));
  // 新增状态管理弹窗
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState(null);
  const navigate = useNavigate();
  const [array, setArray] = useState([
    { name: "全部", status: 1 },
    { name: "待支付", status: 2 },
    { name: "已取消", status: 3 },
    { name: "已支付", status: 4 },
    { name: "已退款", status: 5 }
  ]);

  // 用户信息
  const userid = sessionStorage.getItem("userid");
  const nickname = sessionStorage.getItem("nickname");
  const tel = sessionStorage.getItem("tel");

  // 组件加载时获取数据
  useEffect(() => {
    refresh();
  }, []);

  // 订单列表接口请求 - 使用封装API
  const refresh = async () => {
    try {
      const res = await fetchOrderList(userid);
      if (res && res.code === 1) {  // 检查返回状态码
        setOrderdata(res.data);
        setOrderdatas(res.data);
      } else {
        console.error('获取订单列表失败:', res.msg);
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
    }
  };

  // 订单渲染函数
  const orderForm = (data) => {
    if (data.length === 0) {
      return (
        <div className={styles.order}>
          <img style={{ width: '259px', height: '168px', marginTop: '30px' }} id={styles.noneImg} src={noneImg} alt="暂无数据" />
        </div>
      );
    }

    return (
      <div className={styles.order}>
        {data.map((item, i) => (
          <div key={i} className={styles.orderItem}>
            <div className={styles.address}>
              <b>{item.scenic_name}</b>
              <p style={{
                color: item.status == 1 ? "#6fd675" :
                  item.status == 2 ? "#ff6767" :
                    item.status == 3 ? "#bfbfbf" :
                      item.status == 4 ? "#6fd675" :
                        item.status == 5 ? "#6fd675" : ""
              }}>
                {item.status == 1 ? "已完成" :
                  item.status == 2 ? "待支付" :
                    item.status == 3 ? "已取消" :
                      item.status == 4 ? "已支付" :
                        item.status == 5 ? "已退款" : ""}
              </p>
            </div>
            <div className={styles.img} onClick={() => page(i, item.status, item.id, item.scenic_id)}>
              <img
                src={`${imgUrl}${item.img}`}
                alt={item.name}
              />
              <div className={styles.ticket}>
                <div className={styles.imgContent}>
                  <p>{item.name}</p>
                  <b>￥{item.total_price}</b>
                </div>
                <div className={styles.imgContent}>
                  <p>{item.time}</p>
                  <span>x{item.number}</span>
                </div>
                <div className={styles.imgContent}>
                  <p>数量：{item.number}</p>
                  <img src={bttImg} alt="" />
                </div>
              </div>
            </div>
            <div className={styles.three}>
              {renderOrderActions(item, i)}
              {item.status != 1 && (
                <img
                  src={qrCodeImg}
                  alt="二维码"
                  onClick={() => QRcode(i, item.id, item.order_code, item.status, item.total_price, item.number)}
                />
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };
  // 渲染订单操作按钮
  const renderOrderActions = (item, i) => {
    if (item.status == 1) {
      return (
        <div className={styles.threeItem}>
          <p onClick={() => delorder(i, item.id)}>删除订单</p>
          <p onClick={() => twice(item)}>再次购买</p>
          <p style={{ color: "#ffa8d0", border: "1px #ffa8d0 solid" }}>去评价</p>
        </div>
      );
    } else if (item.status == 2) {
      return (
        <div className={styles.threeItem}>
          <p onClick={() => delorder(i, item.id)}>删除订单</p>
          <p onClick={() => gopay(i, item.id, item.status)}>去支付</p>
        </div>
      );
    } else if (item.status == 3) {
      return (
        <div className={styles.threeItem}>
          <p onClick={() => delorder(i, item.id)}>删除订单</p>
        </div>
      );
    } else if (item.status == 4) {
      return (
        <div className={styles.threeItem}>
          <p onClick={() => delorder(i, item.id)}>删除订单</p>
          <p onClick={() => twice(item)}>再次购买</p>
          <p style={{ color: "#ffa8d0", border: "1px #ffa8d0 solid" }}>去评价</p>
        </div>
      );
    } else if (item.status == 5) {
      return (
        <div className={styles.threeItem}>
          <p onClick={() => delorder(i, item.id)}>删除订单</p>
          <p onClick={() => twice(item)}>再次购买</p>
          <p style={{ color: "#ffa8d0", border: "1px #ffa8d0 solid" }}>去评价</p>
        </div>
      );
    }
  };

  // 点击跳转二维码页面
  const QRcode = (i, id, order_code, status, total_price, number) => {
    console.log(i, id);
    sessionStorage.setItem("QRid", id);
    sessionStorage.setItem("QRcode", order_code);
    sessionStorage.setItem("QRstatus", status);
    sessionStorage.setItem("QRshopname", orderdata[i].name);
    sessionStorage.setItem("QRnum", number);
    sessionStorage.setItem("QRnickname", nickname);
    sessionStorage.setItem("QRtel", tel);
    sessionStorage.setItem("QRcreate_time", orderdata[i].create_time);
    sessionStorage.setItem("QRtime", orderdata[i].time);
    sessionStorage.setItem("QRtotal_price", total_price);
    sessionStorage.setItem("QRname", orderdata[i].scenic_name);
    navigate("/code");
  };

  // 订单选项卡的点击事件
  const fifclick = (k, status) => {
    console.log(orderdatas);
    let arr = [];

    if (status === 1) {
      arr = orderdatas;
    } else {
      for (let i = 0; i < orderdatas.length; i++) {
        if (status === orderdatas[i].status) {
          arr.push(orderdatas[i]);
        }
      }
    }

    setOrderdata(arr.length === 0 ? [] : arr);

    // 滚动条样式
    let marginLeft = "";
    switch (status) {
      case 1: marginLeft = "3%"; break;
      case 2: marginLeft = "23%"; break;
      case 3: marginLeft = "43%"; break;
      case 4: marginLeft = "63%"; break;
      case 5: marginLeft = "83%"; break;
    }

    // 更新选项卡样式
    const items = document.querySelectorAll(`.${styles.items}`);
    items.forEach(item => {
      item.style.color = "#63637c";
      item.style.transition = "all 0.5s";
    });

    if (items[k]) {
      items[k].style.color = "#ffc300";
      items[k].style.transition = "all 0.5s";
    }

    // 更新高亮条的位置
    const highlightBar = document.querySelector(`.${styles.optionsDiv} div`);
    if (highlightBar) {
      highlightBar.style.marginLeft = marginLeft;
      highlightBar.style.transition = "all 0.5s"; // 添加过渡效果
    }
  };
  const [jingqu, setjingqu] = useState(JSON.parse(sessionStorage.getItem("jingqu")) || []);
  console.log(jingqu);
  // 再次购买
  // 再次购买
  const twice = (item) => {
    sessionStorage.setItem("numstate", false);
    const unitPrice = item.total_price / item.number;
    sessionStorage.setItem("deata", JSON.stringify(item));
    sessionStorage.setItem("unitPrice", unitPrice);
    sessionStorage.setItem("numding", item.number);
    sessionStorage.setItem("nickname", nickname);
    sessionStorage.setItem("jingid", item.scenic_id); // 存储当前景区id
    const filteredData = jingqu.filter(jingquItem => jingquItem.id === item.scenic_id);
    console.log('筛选后的数据:', filteredData);
    sessionStorage.setItem("jingdata", JSON.stringify(filteredData[0]));
    navigate("/scenicdetails");
  };


  // 跳转订单详情
  const page = (i, status, id, scenic_id) => {
    console.log(i, status, id, scenic_id);
    sessionStorage.setItem("orderdata", JSON.stringify(orderdata[i]));
    sessionStorage.setItem("orderid", id);
    sessionStorage.setItem("orderstatus", status);
    sessionStorage.setItem("scenic_id", scenic_id); // 存储 scenic_id
    console.log('scenic_id:', scenic_id); // 在控制台打印 scenic_id
    navigate("/orderDetails");
  };

  // 返回上一页
  const left = () => {
    navigate(-1);
  };

  // 跳转首页
  const first = () => {
    navigate("/home");
  };

  // 删除订单
  // 修改后的删除订单函数
  const delorder = (i, id) => {
    setSelectedOrderId(id);
    setIsDeleteModalVisible(true);
  };
  // 确认删除函数 - 使用封装API
  const handleConfirmDelete = async () => {
    if (!selectedOrderId) return;

    try {
      await deleteOrder(selectedOrderId);
      refresh();
      setIsDeleteModalVisible(false);
      setSelectedOrderId(null);
    } catch (error) {
      console.error('删除订单失败:', error);
    }
  };
  // 去支付
  // 去支付 - 使用封装API
  const gopay = async (i, id, status) => {
    console.log(i);
    let state;
    if (status == 2) {
      state = 4;
    }

    try {
      await updateOrderStatus(userid, state, id);
      refresh();
    } catch (error) {
      console.error('更新订单状态失败:', error);
    }
  };

  // 渲染景区数据（你可能还喜欢）
  const rander = () => {
    return data.slice(0, 3).map((item, i) => (
      <div key={i} className={styles.libVideo} onClick={() => details(item, i)}>
        <img src={`${imgUrl}${item.img}`} alt={item.name} />
        <div className={styles.content}>
          <b>{item.name}</b>
          <div className={styles.twoBlock}>
            <p className={styles.play}>游玩榜</p>
            <p className={styles.new}>新乡&nbsp;景区榜第1名</p>
          </div>
          <div className={styles.allstart}>
            {renderStars(item.score)}
            <div className={styles.startText}>
              <span>{item.score}分</span>
              <p>1000条评价</p>
            </div>
          </div>
          <span id={styles.distance} style={{ marginLeft: '6px' }}>距离你26km</span>
          <div className={styles.today}>
            <p>可订明日</p>
            <div className={styles.door}>
              <p>门票</p>
              <span>￥</span>
              <b>80</b>
              <p style={{ marginLeft: "-5px" }}>起</p>
            </div>
          </div>
          <div className={styles.player}>
            {item.must == null ? "" : (<><b>必玩</b>•<span>{item.must}</span></>)}
          </div>
        </div>
      </div>
    ));
  };

  // 渲染星星评分
  const renderStars = (score) => {
    const stars = [];
    const fullStars = Math.floor(score);
    const hasHalfStar = score % 1 >= 0.5;

    for (let i = 1; i <= 5; i++) {
      if (i <= fullStars) {
        stars.push(<img key={i} src={starttwoImg} alt="满星" />);
      } else if (i === fullStars + 1 && hasHalfStar) {
        stars.push(<img key={i} src={starthreeImg} alt="半星" />);
      } else {
        stars.push(<img key={i} src={startoneImg} alt="空星" />);
      }
    }

    return <div className={styles.start}>{stars}</div>;
  };

  // 跳转景区详情 - 已修复
  const details = (item, index) => {
    sessionStorage.setItem("jingid", item.id);
    sessionStorage.setItem("jingdata", JSON.stringify(item));
    navigate("/scenicdetails");
  };

  return (
    <div style={{ backgroundColor: '#f4f4f4' }}>
      {/* 新增删除确认弹窗 */}
      {isDeleteModalVisible && (
        <div className={styles.deleteModalOverlay}>
          <div className={styles.deleteModal}>
            <div className={styles.modalContent}>
              <h3>确认删除</h3>
              <p>确定要删除该订单吗？此操作不可恢复。</p>
              <div className={styles.modalButtons}>
                <button
                  className={styles.cancelButton}
                  onClick={() => {
                    setIsDeleteModalVisible(false);
                    setSelectedOrderId(null);
                  }}
                >
                  取消
                </button>
                <button
                  className={styles.confirmButton}
                  onClick={handleConfirmDelete}
                >
                  确认删除
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      {/* 顶部导航 */}
      <div className={styles.top}>
        <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', width: '50%', justifyContent: 'space-between' }}>
          <div className={styles.left}>
            <img src={leftImg} alt="返回" onClick={left} />
            <div className={styles.line}></div>
            <img id={styles.hourse} src={hourse3Img} alt="首页" onClick={first} />
          </div>
        </div>
        <p>订单</p>
      </div>

      {/* 选项卡 */}
      <div className={styles.option}>
        <div className={styles.options}>
          {array.map((item, i) => (
            <div key={i} className={styles.items} onClick={() => fifclick(i, item.status)}>
              <p>{item.name}</p>
            </div>
          ))}
        </div>
        <div className={styles.optionsDiv}>
          <div></div>
        </div>
      </div>

      {/* 订单列表 */}
      {orderForm(orderdata)}

      {/* 你可能还喜欢 */}
      <div className={styles.like}>
        <div></div>
        <b>你可能还喜欢</b>
        <div></div>
      </div>

      {/* 推荐景区 */}
      <div className={styles.item}>
        {rander()}
      </div>
    </div>
  );
};

export default OrderPage;